/*测试数据*/
var usertestdata=[
	{
		id: 1,
		userId: 2322,
		phone: 18817802281,
		realName: 'lisd',
		address: '上海市浦东新区',
		shoppingAddress: '上海市浦东新区',
		createTime: 1502937009,
		userMoney: 2366,
		taxType: '个人', //公司、个人
		taxCompany: '上海煜众网络科技有限公司',
		taxId: 'CX343344343',
		taxPhone: '18817802221',
		taxAddress: '上海工商银行宝山支行',
		taxBankId: '33222331453233434',
		taxBankName: '上海工商银行宝山支行'
	},
	{
		id: 2,
		userId: 2322,
		phone: 18817802281,
		realName: 'lisd',
		address: '上海市浦东新区',
		shoppingAddress: '上海市浦东新区',
		createTime: 1502937009,
		userMoney: 2366,
		taxType: '个人', //公司、个人
		taxCompany: '上海煜众网络科技有限公司',
		taxId: 'CX343344343',
		taxPhone: '18817802221',
		taxAddress: '上海工商银行宝山支行',
		taxBankId: '33222331453233434',
		taxBankName: '上海工商银行宝山支行'
	}
];
var protestdata=[
	{
		id: 1,
		productID: 2322,
		productName: "18817802281",
		productBrand: 'linda',
		productVersion: 'V3高规',
		store: 3455,
		singlePrice: 234,
		tradeCnt: 2234,
		createTime: 1502937009
	},
	{
		id: 2,
		productID: 334,
		productName: "18817802281",
		productBrand: 'linda',
		productVersion: 'V3高规',
		store: 3455,
		singlePrice: 234,
		tradeCnt: 2234,
		createTime: 1502937009
	}
];


var isKF=true;
$(function(){
	var tgid=getUrlParam("tgid");
	if(tgid!=null && tgid!=""){
		getProductDataMes();
	}
	getLoginUser();
	$("#productSearch").on('click',function(){
		searchProductData();
	});
	$("#productKeys").bind("keydown", function (e) {
		var key = e.which;
		if (key == 13){
			searchProductData();
		}
	});
	$("#userSearch").on('click',function(){
		searchUserData();
	});
	$("#userKeys").bind("keydown", function (e) {
		var key = e.which;
		if (key == 13){
			searchUserData();
		}
	});
	
	
	orderNumChange();

    $("#clearUserSearch").on('click',function(){
        $("#userList").empty();
    });

    $("#clearProductSearch").on('click',function(){
        $("#proList").empty();
    });

	$("#btnCreateOrder").on('click',function(){
		createOrder();
	});
});
/*删除选购产品*/
function deleteBuyProduct(obj) {
    if(obj!=null){
        $(obj).parents(".buy-item").remove();
        console.log($(".buy-item").length);
        if($(".buy-item").length<=0){
            var $tr =$("<tr>").attr({"id":"noProductList"});
            var $td = $("<td>").attr({"colspan":9}).addClass("text-center").text("暂无选购产品！");
            $tr.append($td);
            $("#buyProList").append($tr);
		}else{
			$("#noProductList").remove();
		}
    }
}
/*选购产品展示*/
function addNewProduct(obj) {
	if(obj!=null){
		var productIDs= $(".buy-productID").text();
        var productId=$(obj).parents(".product-item").children(".productID").text();
        var productName=$(obj).parents(".product-item").children(".productName").text();
        var productBrand=$(obj).parents(".product-item").children(".productBrand").text();
        var productVersion=$(obj).parents(".product-item").children(".productVersion").text();
        var store=$(obj).parents(".product-item").children(".store").text();
        var singlePrice=$(obj).parents(".product-item").children(".singlePrice").text();
        var productNum=$(obj).parents(".product-item").children(".productNum").children(".num-product").val();
        if((productNum*1)>(store*1)){
            consoleMes($("#manageContent"),3000,"warning","购买数量大于库存，无法加入！");
		}else{
            $("#noProductList").remove();
            if(productIDs.indexOf(productId)>=0){
				var num=$("#num"+productId).val();
				var tNum=(productNum*1)+(num*1);
				if(tNum>(store*1)){
                    tNum=(store*1);
                    consoleMes($("#manageContent"),3000,"warning","购买数量不能大于库存！");
				}
                $("#num"+productId).val(tNum);
                $("#price"+productId).val(singlePrice);
                $("#totalprice"+productId).text((tNum*1)*(singlePrice*1));
                $("#buy"+productId).val(productId+"@"+tNum+"@"+singlePrice);
			}else{
                var userRole= localStorage.getItem("userRole");
                var $successtr =$("<tr>").addClass("success buy-item");
                var $productID =$("<td>").addClass("buy-productID").text(productId).attr({"tgid":productId});
                var $productName =$("<td>").addClass("buy-productName").text(productName);
                var $productBrand =$("<td>").addClass("buy-productBrand").text(productBrand);
                var $productVersion =$("<td>").addClass("buy-productVersion").text(productVersion);
                var $store =$("<td>").addClass("buy-store").text(store);
                if(userRole=="7001"){
                    var $editSinglePrice =$("<input>").addClass("edit-singlePrice").attr({"id":"price"+productId,"type":"number","min":"0.00","onchange":"editSinglePrice(this)"}).val(singlePrice);
                    var $singlePrice=$("<td>").addClass("buy-singlePrice");
                    $singlePrice.append($editSinglePrice);
                }else{
                    var $singlePrice =$("<td>").addClass("buy-singlePrice").text(singlePrice);
                }
                var $productNum =$("<input>").addClass("productNum").attr({"id":"num"+productId,"type":"number","min":"1","max":store,"onchange":"editProductNum(this)"}).val(productNum);
                var $pnumTd = $("<td>").addClass("td-productNum");
                $pnumTd.append($productNum);
                var $totalPrice =$("<td>").addClass("totalPrice").attr({"id":"totalprice"+productId}).text((productNum*1)*(singlePrice*1));
                var $buyBtntd =$("<td>").addClass("product-mes-list");
                var $buyBtn = $("<input>").addClass("btn btn-primary delete-product").attr({"type":"button","onclick":"deleteBuyProduct(this);"}).val("删除");
                $buyBtntd.append($buyBtn);
                var $buyPIdAndNum = $("<input>").addClass("buy-product-mes").attr({"id":"buy"+productId,"type":"text","hidden":"hidden"}).val(productId+"@"+productNum+"@"+singlePrice);
                $buyBtntd.append($buyPIdAndNum);
                $successtr.append($productID,$productName,$productBrand,$productVersion,$store,$singlePrice,$pnumTd,$totalPrice,$buyBtntd);
                $("#buyProList").append($successtr);
			}
		}
	}


}
/*选购产品价格修改*/
function editSinglePrice(obj) {
    var singlePrice=  $(obj).val().trim();
    var substr=$(obj).parent(".buy-singlePrice").nextAll(".product-mes-list").children(".buy-product-mes").val();
    substr=substr.substring(0,substr.lastIndexOf("@"));
    var tNum=$(obj).parent(".buy-singlePrice").nextAll(".td-productNum").children(".productNum").val().trim();
    $(obj).parent(".buy-singlePrice").nextAll(".totalPrice").text((tNum*1)*(singlePrice*1));
    $(obj).parent(".buy-singlePrice").nextAll(".product-mes-list").children(".buy-product-mes").val(substr+"@"+singlePrice);
}
/*选购产品数量修改*/
function editProductNum(obj) {
    var tNum=  $(obj).val().trim();
    tNum = parseInt(tNum);
    var substr=$(obj).parent(".td-productNum").nextAll(".product-mes-list").children(".buy-product-mes").val();
    var singlePrice=substr.substring(substr.lastIndexOf("@")+1,substr.length);
    var productId=substr.substring(0,substr.indexOf("@"));
    var store =$(obj).parent(".td-productNum").prevAll(".buy-store").text();
    store = parseInt(store);
    if(store<tNum){
        tNum=store;
        consoleMes($("#manageContent"),3000,"warning","购买数量不能大于库存！");
    }
    $(obj).val(tNum);
    $(obj).parent(".td-productNum").nextAll(".totalPrice").text((tNum*1)*(singlePrice*1));
    $(obj).parent(".td-productNum").nextAll(".product-mes-list").children(".buy-product-mes").val(productId+"@"+tNum+"@"+singlePrice);
}
/*产品信息展示*/
function productMesShow(datarow){
	if(datarow!=null){
		if(datarow.length==undefined){
			var arr=[];
            arr.push(datarow);
            datarow=arr;
		}
		if(datarow.length>0){
            $("#proList").empty();
            $.each(datarow, function(i,item) {
                var $successtr =$("<tr>").addClass("success product-item");
                /*var $productrd =$("<td>").addClass("productrd");*/
                var $productID =$("<td>").addClass("productID").text(item.productId);
                var $productName =$("<td>").addClass("productName").text(item.productName);
                var $productBrand =$("<td>").addClass("productBrand").text(item.productBrand);
                var $productVersion =$("<td>").addClass("productVersion").text(item.productVersion);
                var $store =$("<td>").addClass("store").text(item.store);
                var $singlePrice =$("<td>").addClass("singlePrice").text(item.singlePrice);
                var $tradeCnt =$("<td>").addClass("tradeCnt").text(item.tradeCnt);

                /*var $radioIndex =$("<input>").addClass("radio-product").attr({'type':'radio','name':'proitem','singlePrice':item.singlePrice,'onclick':'productRadioSeleted(this)'}).val(item.productId);*/
                /*$productrd.append($radioIndex);*/

                var $buyNumtd =$("<td>").addClass("productNum");
                var $buyNum = $("<input>").addClass("num-product").attr({"type":"number","min":0,"max":item.store}).val(1);
                $buyNumtd.append($buyNum);
                var $buyBtntd =$("<td>").addClass("");
                var $buyBtn = $("<input>").addClass("btn btn-primary num-product").attr({"type":"button","onclick":"addNewProduct(this);"}).val("加入");
                $buyBtntd.append($buyBtn);

                $successtr.append($productID,$productName,$productBrand,$productVersion,$store,$singlePrice,$tradeCnt,$buyNumtd,$buyBtntd);
                $("#proList").append($successtr);
            });
		}else{
            consoleMes($("#manageContent"),3000,"warning","无相关数据！");//success、info、warning、danger
        }

	}else{
        consoleMes($("#manageContent"),3000,"warning","无相关数据，请重试！");//success、info、warning、danger
    }
};
/*搜索产品时*/
function searchProductData(){
	var productKeys= $("#productKeys").val().trim();
	if(productKeys!=null && productKeys!=""){
		/*var datarow = protestdata;
		productMesShow(datarow);*/
        $.post(
            gobalServer+"product/query",
            {"keyword":productKeys,"containZero":2},
            function(backData){
                if(backData.statusCode==200){
                    var datarow=backData.commonList;
                    productMesShow(datarow);
                }else{
                    consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
                }
            }
        );
	}else{
		consoleMes($("#manageContent"),3000,"warning","请输入要搜索的关键字");
	}
};
/*从产品查询开单按钮跳转过来*/
function getProductDataMes(){
	var tgid=getUrlParam("tgid");
	if(tgid!=null && tgid!=""){
		/*var datarow = protestdata;
		productMesShow(datarow);*/
        $.post(
            gobalServer+"product/selectOne",
            {"productId":tgid},
            function(backData){
                if(backData.statusCode==200){
                    var datarow=backData.object;
                    productMesShow(datarow);
                }else{
                    consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
                }
            }
        );

	}
};
/*客户信息展示*/
function userMesShow(datarow){
    if(datarow!=null){
        if(datarow.length==undefined){
            var arr=[];
            arr.push(datarow);
            datarow=arr;
        }
        if(datarow.length>0){
            $("#userList").empty();
            $.each(datarow, function(i,item) {
                var $successtr =$("<tr>").addClass("success user-item");
                var $userrd =$("<td>").addClass("userrd");
                var $userId =$("<td>").addClass("userId").text(item.userId);
                var $realName =$("<td>").addClass("realName").text(item.realName);
                var $phone =$("<td>").addClass("phone").text(item.phone);
                var $userMoney =$("<td>").addClass("userMoney").text(item.userMoney);
                var $address =$("<td>").addClass("address").text(item.address);
                var $shoppingAddress =$("<td>").addClass("shoppingAddress").text(item.shoppingAddress);
                var $radioIndex =$("<input>").addClass("radio-user").attr({'type':'radio','name':'useritem',"shoppingAddress":item.shoppingAddress,'onclick':'userRadioSeleted(this)'}).val(item.userId);
                $userrd.append($radioIndex);
                $successtr.append($userrd,$userId,$realName,$phone,$userMoney,$address,$shoppingAddress);

				/*展示开票信息*/
                var $infotr =$("<tr>").addClass("info user-item");
                var $taxMes =$("<td>").addClass("taxMes").attr({'colspan':7});
                var $taxh5=$("<h5>").text("客户:"+item.realName+"的开票信息：");
                var $taxType=$("<label>").addClass("label-ml").text("开票类型："+item.taxType);
                var $taxCompany=$("<label>").addClass("label-ml").text("开票公司："+item.taxCompany);
                var $taxId=$("<label>").addClass("label-ml").text("税务账号："+item.taxId);
                var $taxPhone=$("<label>").addClass("label-ml").text("开票电话："+item.taxPhone);
                var $taxAddress=$("<label>").addClass("label-ml").text("开票地址："+item.taxAddress);
                var $taxBankId=$("<label>").addClass("label-ml").text("开户行账户："+item.taxBankId);
                var $taxBankName=$("<label>").addClass("label-ml").text("开户行名称："+item.taxBankName);
                $taxMes.append($taxh5,$taxType,$taxCompany,$taxId,$taxPhone,$taxAddress,$taxBankId,$taxBankName);
                $infotr.append($taxMes);

                $("#userList").append($successtr,$infotr);
            });
        }else{
            consoleMes($("#manageContent"),3000,"warning","无相关数据！");//success、info、warning、danger
        }

    }else{
        consoleMes($("#manageContent"),3000,"warning","无相关数据，请重试！");//success、info、warning、danger
    }

};
/*搜索客户时*/
function searchUserData(){
	var userKeys= $("#userKeys").val().trim();
	if(userKeys!=null && userKeys!=""){
		/*var datarow = usertestdata;
		userMesShow(datarow);*/
        $.post(
            gobalServer+"user/query",
            {"keyword":userKeys},
            function(backData){
                if(backData.statusCode==200){
                    var datarow=backData.commonList;
                    userMesShow(datarow);
                }else{
                    consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
                }
            }
        );
	}else{
		consoleMes($("#manageContent"),3000,"warning","请输入要搜索的关键字");
	}
};
/*获取登录用户,若为客户,直接显示信息*/
function getLoginUser(){
	/*if(1==1){
		isKF=true;
		$("#userForm").hide();
		var datarow = usertestdata;
		userMesShow(datarow);	
	}else{
		isKF=false;
		$("#userForm").show();
	}*/
    var tgid = localStorage.getItem("userID");
    if(tgid!=null && tgid!=""){
        $.post(
            gobalServer+"user/selectOne",
            {"userId":tgid},
            function(backData){
                if(backData.statusCode==200){
                    if(backData.object!=null &&backData.object.permission ==7002){
                        isKF=true;
                        $("#userForm").hide();
                        var datarow = backData.object;
                        userMesShow(datarow);
                    }else{
                        isKF=false;
                        $("#userForm").show();
                    }

                }else{
                    consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
                }
            }
        );
    }else{
        consoleMes($("#manageContent"),3000,"warning","无法获取个人信息，可能账号未登录，请重新登录！");//success、info、warning、danger
        setTimeout(function () {
            window.location.href=gobalWeb+"login.html";
        }, 2500);
    }

};
/*产品radio选择事件*/
function productRadioSeleted(obj){
	var ordernum=$("#ordernum").val().trim();
	if(ordernum!=null && ordernum>=1){
		var singlePrice=$(obj).attr('singlePrice');
		$("#orderTotal").text(singlePrice*ordernum);
	}
};
/*客户radio选择事件*/
function userRadioSeleted(obj){
	var shoppingAddress=$(obj).attr('shoppingAddress');
	$("#orderAddress").val(shoppingAddress);
    $(obj).parent(".userrd").parent(".user-item.success").prevAll(".user-item").remove();
    $(obj).parent(".userrd").parent(".user-item.success").next(".user-item.info").nextAll(".user-item").remove();
};
/*订单数量改变时间事件*/
function orderNumChange(){
	$("#ordernum").unbind().change(function(obj){
		var proid=$("input[name='proitem']:checked").val();
		if(proid!=null && proid!=""){
			var singlePrice=$("input[name='proitem']:checked").attr('singlePrice');
			var ordernum=$("#ordernum").val().trim();
			$("#orderTotal").text(singlePrice*ordernum);
		}
	});
};
/*开单*/
function createOrder(){
	var proids="";
    $(".buy-product-mes").each(function (i,obj) {
        if(i!=0){
            proids+="#";
        }
        proids+=$(obj).val().trim();
    });
	var userid=$("input[name='useritem']:checked").val();
	var orderAddress=$("#orderAddress").val().trim();
    var realName=$("#realName").val().trim();
    var userPhone=$("#userPhone").val().trim();
    var orderRemark=$("#reMark").val().trim();
    if(userid==null || userid==""){
        consoleMes($("#manageContent"),2000,"warning","请选择开店客户！");
        return;
    }
	if(proids==null || proids.length<=0){
		consoleMes($("#manageContent"),2000,"warning","请选购开单产品！");
		return;
	}
	if(orderAddress==null || orderAddress==""){
		consoleMes($("#manageContent"),2000,"warning","请输入送货地址！");
		return;
	}
    if(realName==null || realName==""){
        consoleMes($("#manageContent"),2000,"warning","请输入真实姓名！");
        return;
    }
    //if(userPhone==null || userPhone=="" || !ischeckmobile(userPhone)){
    //    consoleMes($("#manageContent"),2000,"warning","请输入正确的联系方式！");
    //    return;
    //}
    if(userPhone==null || userPhone==""){
        consoleMes($("#manageContent"),2000,"warning","请输入正确的联系方式！");
        return;
    }
	/*consoleMes($("#manageContent"),2000,"success","开单成功！");//success、info、warning、danger
	setTimeout(function () {
		if(isKF){
			window.location.href=gobalWeb+"orders/userorders.html";
		}else{
			window.location.href=gobalWeb+"orders/orders.html";
		}
    }, 2500);*/
    $.post(
        gobalServer+"order/insertOrdersByProductIds",
        {"productIdsAndNumbers":proids,"userId":userid,"shoppingAddress":orderAddress,"realName":realName,"userPhone":userPhone,"orderRemark":orderRemark},
        function(backData){
            if(backData.statusCode==200){
                consoleMes($("#manageContent"),2000,"success",backData.msg);//success、info、warning、danger
                setTimeout(function () {
                    if(isKF){
                        window.location.href=gobalWeb+"orders/userorders.html";
                    }else{
                        window.location.href=gobalWeb+"orders/orders.html";
                    }
                }, 2500);
            }else{
                consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
            }
        }
    );

		
};
